package xyz.chaobei.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/3/1
 */
public class HttpClientTest {

    @Test
    public void test1() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx602550907247c3f5&secret=b4a11f91f0438406b617d8331af70eaf");

        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();

            InputStream inputStream = responseEntity.getContent();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int index = 0;
            while ((index = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, index);
            }
            System.out.println(byteArrayOutputStream.toString());
            inputStream.close();
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test2() {

        List<NameValuePair> value = new ArrayList<>();

        value.add(new BasicNameValuePair("grant_type","desc"));
        value.add(new BasicNameValuePair("appid","1234"));

        String code = URLEncodedUtils.format(value,"UTF-8");
        System.out.println(code);
    }

}
